package com.xiyan.blog.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xiyan.blog.entity.User;
import com.xiyan.blog.service.IUserService;
import com.xiyan.blog.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(value = "用户", tags = "用户api")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    @ApiOperation("新增用户")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult add(@RequestBody User user) {
        try {
            if (ObjectUtil.isNull(user)) {
                return ResponseResult.error().message("新增的用户为空");
            }

            // TODO: 验证手机号、验证用户名唯一性
            userService.saveOrUpdate(user);
            return ResponseResult.ok();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.error().message("新增失败");
        }
    }

    @ApiOperation("删除用户")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseResult delete(@PathVariable("id") String id) {
        try {
            if (StrUtil.isEmpty(id)) {
                return ResponseResult.error().message("用户id为空");
            }
            userService.removeById(id);
            return ResponseResult.ok();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.error().message("删除失败，用户ID不存在");
        }
    }

    @ApiOperation("用户列表")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult list() {
        try {
            List<User> users = userService.list();
            return ResponseResult.ok().data(users);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.error().message("获取用户列表失败");
        }
    }

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getById(@PathVariable("id") String id) {
        try {
            if (StrUtil.isEmpty(id)) {
                return ResponseResult.error().message("用户id为空");
            }

            User user = userService.getById(id);
            return ResponseResult.ok().data(user);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.error().message("获取用户信息失败");
        }
    }

    // TODO: 多条件分页查询
}
